import sha1 from 'sha1'
import config from '@/config'
import { visibleWeather } from '@/utils/krpano'

export const currentUrl = _ => window.location.href

export const isInteraction = () => {
  return currentUrl().indexOf('ismaster') > -1
}
// 检查状态
export const getStatus = res =>
  !!res.status && res.data && Object.is(res.data.code, config.errno)

// 获取设备 pc true : app false
const sUserAgent = navigator.userAgent.toLowerCase()
export const getPlatform = () => {
  const bIsIpad = sUserAgent.match(/ipad/i) == 'ipad'
  const bIsIphoneOs = sUserAgent.match(/iphone os/i) == 'iphone os'
  const bIsMidp = sUserAgent.match(/midp/i) == 'midp'
  const bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == 'rv:1.2.3.4'
  const bIsUc = sUserAgent.match(/ucweb/i) == 'ucweb'
  const bIsAndroid = sUserAgent.match(/android/i) == 'android'
  const bIsCE = sUserAgent.match(/windows ce/i) == 'windows ce'
  const bIsWM = sUserAgent.match(/windows mobile/i) == 'windows mobile'

  if (
    bIsIpad ||
    bIsIphoneOs ||
    bIsMidp ||
    bIsUc7 ||
    bIsUc ||
    bIsAndroid ||
    bIsCE ||
    bIsWM
  ) {
    return false
  } else {
    return true
  }
}

// iPad
export const isPad = () => {
  return sUserAgent.match(/ipad/i) == 'ipad'
}
// ios
export const isIos = () => {
  return (
    sUserAgent.match(/ipad/i) == 'ipad' ||
    sUserAgent.match(/iphone os/i) == 'iphone os'
  )
}

// Mobile
export const isMobile = () => {
  return !getPlatform()
}

/**
 * 获取设备/平台类型
 *
 * @param {String} device device/platform name lowercase
 * @returns {Boolean} boolean
 */
export const getDeviceType = device => {
  const ua = navigator.userAgent.toLowerCase()
  const list = {
    ie: ua.includes('trident'), // IE内核
    mobile: !!ua.match(/applewebkit.*mobile.*/), // 是否为移动终端
    ios: !!ua.match(/\(i[^;]+;( u;)? cpu.+mac os x/), // ios终端
    android: ua.includes('android') || ua.includes('linux'), // android终端
    iphone: ua.includes('iphone'), // 是否为iPhone
    ipad: ua.includes('ipad'), // 是否iPad
    wx: ua.includes('micromessenger'), // 是否微信
    pc: !ua.match(/applewebkit.*mobile.*/) && !ua.includes('ipad'), // 是否iPad
  }
  !list.hasOwnProperty(device) &&
    console.error('utils.getDeviceType arguments error')
  return list[device]
}

// PC
export const isPc = () => {
  return getPlatform()
}

// 是否微信浏览器
export const isWxBrowser = () => {
  const ua = window.navigator.userAgent.toLowerCase()
  return ua.match(/MicroMessenger/i) == 'micromessenger'
}

// IP
export const getIP = () => {
  return returnCitySN.cip || ''
}

// 视口
export const getViewport = () => {
  const VW = screen.width || window.innerWidth
  const VH = screen.height || window.innerHeight
  return {
    VW,
    VH,
  }
}

// 设置模板样式
export const getThemeName = () => {
  return getPlatform() ? 'pc' : 'app'
}

// 是否新窗口打开
export const openNewWindow = href => {
  // 如果本地是https,要访问的iframe地址不是https的话，需要新窗口打开
  if (
    window.location.protocol.indexOf('https') !== -1 &&
    href.indexOf('https') === -1
  ) {
    return true
  } else {
    if (href.indexOf('wechat') != -1) {
      return true
    } else {
      return false
    }
  }
}

const _sign = (ticket, timestamp, noncestr) => {
  let params = [noncestr, ticket, timestamp]
  let str = params.sort().join('')
  let sha = sha1(str)
  return sha
}

const createNonce = () =>
  Math.random()
    .toString(36)
    .substr(2, 15)
const createTimestamp = () => parseInt(new Date().getTime() / 1000, 10) + ''

export const sign = (ticket, url) => {
  var noncestr = createNonce()
  var timestamp = createTimestamp()
  var signature = _sign(ticket, timestamp, noncestr)

  return {
    noncestr: noncestr,
    timestamp: timestamp,
    signature: signature,
  }
}

// 格式化时间
export const formatDate = (date, fmt) => {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length),
    )
  }

  let obj = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
  }

  for (let s in obj) {
    if (new RegExp(`(${s})`).test(fmt)) {
      let str = obj[s] + ''
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : ('00' + str).substr(str.length),
      )
    }
  }
  return fmt
}

// 天气
export const getWeather = city => {
  if (!visibleWeather()) return
  const s = new Seniverse($globalconfig.xzID, $globalconfig.xzKey, {
    api: 'daily',
    callback: 'getData',
    location: city || 'beijing',
    language: 'zh-Hans',
  })
  // console.log(s)
  return s
}

// 设置微信title
export const setWechatTitle = title => {
  document.title = title
  if (isWxBrowser()) {
    var iframe = document.createElement('iframe')
    iframe.style.display = 'none'
    // 替换成站标favicon路径或者任意存在的较小的图片即可
    iframe.setAttribute('src', '/favicon.ico')
    var iframeCallback = function() {
      setTimeout(function() {
        iframe.removeEventListener('load', iframeCallback)
        document.body.removeChild(iframe)
      }, 0)
    }
    iframe.addEventListener('load', iframeCallback)
    document.body.appendChild(iframe)
  }
}

// 获取字符长度
export const getTextLength = str => {
  return String(str).replace(/[^\x00-\xff]/g, 'aa').length
}

// 阻止拖动
export const handleDefPrevent = e => {
  e.preventDefault()
}

// 防抖
const throttle = (fn, wait) => {
  let inThrottle, lastFn, lastTime
  return function() {
    let ctx = this
    let args = arguments
    if (!inThrottle) {
      fn.apply(ctx, args)
      lastTime = Date.now()
      inThrottle = true
    } else {
      clearTimeout(lastFn)
      lastFn = setTimeout(function() {
        if (Date.now() - lastTime >= wait) {
          fn.apply(ctx, args)
          lastTime = Date.now()
        }
      }, Math.max(wait - (Date.now() - lastTime), 0))
    }
  }
}

let iLastTouch, delta
// scene双击事件处理
export const doubleClick = e => {
  let iNow = new Date().getTime()

  iLastTouch = iLastTouch || iNow + 1
  delta = iNow - iLastTouch
  if (delta < 200 && delta > 0) {
    return true
  }
  iLastTouch = iNow
}

// 浏览器切换手机模式
let ratio = window.devicePixelRatio
let changeModel = function() {
  setTimeout(() => {
    if (window.devicePixelRatio != ratio) {
      window.location.reload()
    }
  }, 500)
}

// window.addEventListener("resize", changeModel, false)

const toString = Object.prototype.toString
export function isPlainObject(val) {
  return toString.call(val) === '[object Object]'
}

export const isXiaoMiPhone = () => {
  const ua = navigator.userAgent.toLowerCase()
  const isXiaomi = ua.match(/mi\s/i) == 'mi '
  const isXiaomi2s = ua.match(/mix\s/i) == 'mix '
  const isRedmi = ua.match(/redmi/i) == "redmi";

  return isXiaomi || isXiaomi2s || isRedmi
}

// 深克隆
export const DeepCloneData = (data) => {
  if (!data || !(data instanceof Object) || (typeof data === 'function')) {
    return data || undefined
  }
  var constructor = data.constructor
  var result = new constructor()
  for (var key in data) {
    if (data.hasOwnProperty(key)) {
      result[key] = DeepCloneData(data[key])
    }
  }
  return result
}

// 数组排序
export const sortId = (a, b) => {
  return a.sort - b.sort
}

// 判断字符串是否为json格式
export const isJSON = (str) => {
  if (typeof str == 'string') {
    try {
      var obj=JSON.parse(str);
      if (typeof obj == 'object' && obj ) {
        return true;
      } else {
        return false;
      }

    } catch(e) {
      // console.log('error：'+str+'!!!'+e);
      return false;
    }
  }
}

/**
   *限制值在范围内
  *
  * @param {*} val
  * @param {*} min
  * @param {*} max
  * @returns {Number} 范围内 值
  */
export const range = (val, min, max) => {
  return Math.min(Math.max(val, min), max)
}

/**
   * 复制传入的文本到剪贴板
   *
   * @param {String} text 文本
   */
export const copyText = (text) => {
  const tempInput = document.createElement('input')
  tempInput.value = text
  document.body.appendChild(tempInput)
  tempInput.select() // 选择对象
  document.execCommand('Copy') // 执行浏览器复制命令
  document.body.removeChild(tempInput)
  $VM.$vgo.tip('复制成功!', 'success')
}

// 下载文件
export const downfile = (url, name = '') => {
  // 创建隐藏的可下载链接
  var eleLink = document.createElement('a')
  eleLink.download = name
  eleLink.style.display = 'none'
  eleLink.href = url
  // 触发点击
  document.body.appendChild(eleLink)
  eleLink.click()
  // 然后移除
  document.body.removeChild(eleLink)
}

